﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviour {

    public static ObjectPool instance { get; private set;}

    private Dictionary<string, ArrayList> pool = new Dictionary<string, ArrayList> { };
    // Use this for initialization
    void Start()
    {
        instance = this;
        Invoke("Init", 0.5f);
    }

    private void Init() {
        int count = transform.childCount;
        for (int i = 0; i < count; i++)
        {
            ReturnObject(transform.GetChild(i).gameObject);
        }
    }

    public GameObject CreateObject(string key, Vector3 position, Quaternion rotation, bool isInitialize)
    {
        GameObject o;
        //检测列表中是否有要创建的物体，有着拿出来用，没有则新建物体
        if (pool.ContainsKey(key))
        {
            ArrayList list = pool[key];
            //检测列表是否为空，不为空则拿出来用，为空则新建物体
            if (list.Count > 0)
            {
                o = list[0] as GameObject;
                list.RemoveAt(0);
                o.transform.position = position;
                o.transform.rotation = rotation;
                if (isInitialize) o.GetComponent<ObjectPoolBase>().Initialize();
                o.SetActive(true);

            }
            else
            {
                string path = "";
                path = "Prefabs/" + key;
                o = Instantiate(Resources.Load(path), position, rotation) as GameObject;
                o.name = key;
            }
        }
        else
        {
            string path = "";
            path = "Prefabs/" + key;
            o = Instantiate(Resources.Load(path), position, rotation) as GameObject;
            o.name = key;
        }
        return o;
    }

    public Object ReturnObject(GameObject go)
    {
        go.transform.SetParent(transform);
        string key = go.name;
        if (pool.ContainsKey(key))
        {
            ArrayList list = pool[key];
            list.Add(go);
        }
        else
            pool[key] = new ArrayList { go };
        go.SetActive(false);
        go.transform.localScale = Vector3.zero;
        return go;
    }

    public void DestroyThisObject(GameObject go) {
        go.transform.SetParent(transform);
        Destroy(go);
    }
}
